<template>
  <div>
    <el-upload v-bind="$attrs" v-model:file-list="fileList" action="/system/system/v2/file/upload" :data="{
      osType: osType
    }" :headers="{
          Authorization: formatToken(getToken()?.accessToken)
        }" :accept="accept" :multiple="limit > 1" :limit="limit"
      :class="{ 'upload-is-view': (limit === 1 && fileList.length > 0) }" :on-success="handlerSuccess"
      :before-upload="beforeupload" :on-exceed="handlerExceed" :on-error="onError" :on-remove="removeHandler"
      :on-preview="previewLOOK" :addORupdate="addORupdate">
      <el-button type="primary">选择文件</el-button>
      <small class="text-gray-400 ml-1">{{ tips }}</small>
    </el-upload>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, watchEffect } from "vue";
import type { UploadProps, UploadUserFile } from "element-plus";
import { formatToken, getToken, userKey } from "@/utils/auth";
import { removeFileApi } from "@/api/user";
import { message } from "@/utils/message";
import { getFileNameFromPath } from "@/utils/functions"
import { ElMessage } from "element-plus";
import { cloneDeep, storageLocal } from "@pureadmin/utils";
import { PLATFORM_Map, usePageVariablesStoreHook } from "@/store/modules/pageVariables";
interface Props {
  addORupdate?: any,
  files?: UploadUserFile[] | string;
  fileList?: UploadUserFile[];
  limit?: number;
  accept?: string,
  tips?: string,
  osType?: string,
  preview?: {
    type: (file: UploadUserFile) => void,
    default: (file) => {}
  };
}

const emits = defineEmits(["update:files", "update:fileList", "delFile"]);
const props = withDefaults(defineProps<Props>(), {
  files: () => [],
  osType: "qiniu",
  limit: 6,
  accept: ".doc,.docx,.pdf",
  addORupdate: null
});
const tips = ref(`(仅支持${props.accept}文件)`)
const srcList = ref([]);


/**
 * @description:  接收和上传的数据类型共有三种, 1: 字符串, 2: 字符串数组, 3: 空字符串
 * @description:  显示的数据类型: [{url: 'http://xxx.com/xxx.jpg'}]
 */
const fileReset = (files: any) => {
  // 无数据验证: 是空的类型
  if (files === "" || !files) return [];
  // 无数据验证: 是[]
  if (Array.isArray(files) && files.length === 0) return [];
  // 有数据验证: 是字符串类型 http://xxx.com/xxx.jpg
  if (typeof files === "string") {
    return [{ url: files, success: "success", name: getFileNameFromPath(files) }];
  }
  //  有数据验证: 是数组类型
  // [http://xxx.com/xxx.jpg, http://xxx.com/xxx.jpg]
  // [{name: 'xxx', response: {res: 'http://xxx.com/xxx.jpg'}}]
  if (Array.isArray(files) && files.length !== 0) {
    return files.map(file => {
      // console.log("files", files);

      if (typeof file === "string") {
        return { url: file, success: "success" };
      }
      if (typeof file === "object") {
        const response = file.response;

        return response
          ? { url: response.result, uid: file.uid, success: "success", name: file.name }
          : { url: file.url, uid: file.uid, success: "success", name: file.name };
      }
    });
  }
  return [];
};
const fileList = ref(fileReset(props.files));

watchEffect(
  () => {
    srcList.value = fileList.value.map(item => item.url) || [];
  },
  { flush: "post" }
);
// console.log("fileList", props.files);
watch(
  () => props.files,
  file => {
    if (!file || file.length === 0) {
      fileList.value = [];
    }
    fileList.value = fileReset(props.files)


  }
);

/**
 * @description: 查看图片
 */
const previewLOOK: UploadProps["onPreview"] = file => {
  console.log("addORupdate", props.addORupdate);
  if (props.addORupdate == 1) {
    window.open(file.url, '_blank')
  } else {
    if (storageLocal().getItem(userKey)?.userInfo?.roles?.operate.includes('business.mainte.preview')) {
      window.open(file.url, '_blank')
    } else {
      message("无查看合同权限", {
        type: "warning"
      });
    }
  }


};
/**
 * @description: 删除图片
 */
const removeHandler: UploadProps["onRemove"] = file => {
  // const index = fileList.value.findIndex(item => item.url == file.url);
  // fileList.value.splice(index, 1);
  // srcList.value.splice(index, 1);
  emitFileHandler();
  const repson: any = file.response;
  if (file.url) {
    removeFileApi(
      {
        fileUrl: repson ? repson.result.fileUrl : file.url,
        osType: props.osType
      }
      // repson ? {fileUrl: repson.result.fileUrl} : {fileUrl: file.url}
    )
  }

}

const handlerExceed: UploadProps["onExceed"] = () => {
  message("已超过最大上传限制数", {
    type: "warning"
  });
};

const onError: UploadProps["onError"] = () => {
  message("上传失败", {
    type: "error"
  });
};
/**
 * @description: 发送数据
 */
const emitFileHandler = () => {
  const files = fileReset(fileList.value).map(item => {
    return {
      url: item.url,
      name: item.name
    }
  }
  );
  if (props.limit === 1) {
    emits("update:files", files.at(0) ?? "");
  } else {
    emits("update:files", files);
  }
  emits("delFile")
};

const handlerSuccess = (response: any, uploadFile: any, uploadFiles: any) => {
  if (!uploadFiles.some(item => item?.status == 'uploading')) {
    console.log(uploadFiles);

    uploadFiles.forEach((item, index) => {
      if (item?.status != "success" || (item?.response?.code != 200 && !item?.url)) {
        fileList.value = fileList.value.filter(item1 => item1?.uid != item.uid)
        ElMessage({
          type: 'error',
          message: item?.response?.msg ?? `文件${item?.name}上传失败`,
        })
      }
      if (index == uploadFiles.length - 1) {
        emitFileHandler();
      }
    })
  }
};

const beforeupload = (file) => {
  if (props.accept == '.') {
    return true;
  }
  let names = file.name.split(".")
  let extension = `.${names[names.length - 1]}`;
  let extensionList = props.accept.split(",");
  if (extensionList.indexOf(extension) < 0) {
    ElMessage({
      type: 'error',
      message: '文件格式错误',
    })
    return false;
  }
}
</script>

<style scoped lang="scss">
.upload-is-view {
  :deep(.el-upload) {
    display: none;
  }
}
</style>
